import React, { useState } from 'react';
import { 
  Layout, 
  Menu, 
  Avatar, 
  Typography, 
  Divider, 
  Button,
  Tooltip,
  Space
} from 'tdesign-react';
import { 
  PlayIcon, 
  BookIcon, 
  StarIcon, 
  KeyboardIcon,
  DashboardIcon,
  MenuFoldIcon,
  MenuUnfoldIcon
} from 'tdesign-icons-react';

import TypingGameView from '../../views/TypingGameView';
import WordLearning from '../educational/WordLearning';
import EnglishPracticeView from '../../views/EnglishPracticeView';
import AchievementsView from '../achievements/AchievementsView';
import { themeColors, spacing, borderRadius } from '../../theme/theme';

const { Header, Aside, Content } = Layout;
const { Text, Title } = Typography;

const DRAWER_WIDTH = 280;
const DRAWER_WIDTH_COLLAPSED = 72;
const DRAWER_WIDTH_SMALL = 240; // 13寸屏幕适配

const MainNavigation: React.FC = () => {
  const [currentView, setCurrentView] = useState('0');
  const [collapsed, setCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(window.innerWidth < 900);
  const [isSmallScreen, setIsSmallScreen] = useState(window.innerWidth < 1366); // 13寸屏幕判断

  React.useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      setIsMobile(width < 900);
      setIsSmallScreen(width < 1366);
      // 13寸屏幕自动折叠侧边栏
      if (width < 1280 && width >= 900) {
        setCollapsed(true);
      }
    };
    
    window.addEventListener('resize', handleResize);
    // 初始化时也执行一次
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const toggleCollapse = () => {
    setCollapsed(!collapsed);
  };

  const navigationItems = [
    { 
      value: '0', 
      label: '英文练习', 
      icon: <KeyboardIcon />, 
      emoji: '⌨️',
      content: () => <EnglishPracticeView />
    },
    { 
      value: '1', 
      label: '汉字游戏', 
      icon: <PlayIcon />, 
      emoji: '🎮',
      content: () => <TypingGameView />
    },
    { 
      value: '2', 
      label: '汉字学习', 
      icon: <BookIcon />, 
      emoji: '📚',
      content: () => (
        <div style={{ padding: spacing.l }}>
          <WordLearning />
        </div>
      )
    },
    { 
      value: '3', 
      label: '成就中心', 
      icon: <StarIcon />, 
      emoji: '🏆',
      content: () => <AchievementsView />
    },
  ];

  const handleMenuClick = (value: string) => {
    setCurrentView(value);
  };

  const renderCurrentView = () => {
    const currentItem = navigationItems.find(item => item.value === currentView);
    return currentItem ? currentItem.content() : navigationItems[0].content();
  };

  const menuItems = navigationItems.map(item => ({
    value: item.value,
    label: collapsed ? '' : `${item.emoji} ${item.label}`,
    icon: item.icon,
  }));

  const getSidebarWidth = () => {
    if (collapsed) return DRAWER_WIDTH_COLLAPSED;
    if (isSmallScreen) return DRAWER_WIDTH_SMALL;
    return DRAWER_WIDTH;
  };

  const sidebarStyle: React.CSSProperties = {
    width: getSidebarWidth(),
    backgroundColor: themeColors.backgroundContainer,
    borderRight: `1px solid ${themeColors.border.level1}`,
    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.05)',
    transition: 'width 0.3s ease',
    position: 'fixed',
    height: '100vh',
    top: 0,
    left: 0,
    zIndex: 1000,
    overflow: 'hidden'
  };

  const headerSectionStyle: React.CSSProperties = {
    padding: collapsed ? spacing.m : spacing.l,
    textAlign: 'center',
    background: `linear-gradient(135deg, ${themeColors.primary} 0%, ${themeColors.secondary} 100%)`,
    color: '#ffffff',
    position: 'relative',
    minHeight: collapsed ? '80px' : '120px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center'
  };

  const statsCardStyle: React.CSSProperties = {
    margin: collapsed ? `${spacing.s} ${spacing.xs}` : `${spacing.m} ${spacing.s}`,
    padding: collapsed ? spacing.s : spacing.m,
    backgroundColor: themeColors.gray[50],
    borderRadius: borderRadius.large,
    border: `1px solid ${themeColors.border.level2}`,
  };

  const contentStyle: React.CSSProperties = {
    minHeight: '100vh',
    overflow: 'auto',
    width: isMobile ? '100%' : `calc(100% - ${getSidebarWidth()}px)`,
    marginLeft: isMobile ? 0 : getSidebarWidth(),
    transition: 'all 0.3s ease',
    padding: 0,
    boxSizing: 'border-box',
    display: 'flex',
    justifyContent: 'center'
  };

  const contentInnerStyle: React.CSSProperties = {
    width: '100%',
    maxWidth: isSmallScreen ? '100%' : '1400px',
    boxSizing: 'border-box'
  };

  const collapseButtonStyle: React.CSSProperties = {
    position: 'absolute',
    bottom: spacing.m,
    right: spacing.s,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    color: '#ffffff',
    border: 'none',
    borderRadius: borderRadius.medium,
    width: '32px',
    height: '32px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    transition: 'background-color 0.2s ease'
  };

  const mobileMenuStyle: React.CSSProperties = {
    position: 'fixed',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: themeColors.backgroundContainer,
    borderTop: `1px solid ${themeColors.border.level1}`,
    padding: spacing.s,
    display: 'flex',
    justifyContent: 'space-around',
    zIndex: 1000
  };

  if (isMobile) {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        <Content style={{ paddingBottom: '80px' }}>
          {renderCurrentView()}
        </Content>
        
        {/* 移动端底部导航 */}
        <div style={mobileMenuStyle}>
          {navigationItems.map((item) => (
            <Button
              key={item.value}
              variant={currentView === item.value ? 'base' : 'text'}
              theme={currentView === item.value ? 'primary' : 'default'}
              size="small"
              onClick={() => handleMenuClick(item.value)}
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                padding: `${spacing.xs} ${spacing.s}`,
                minWidth: '60px',
                height: '50px'
              }}
            >
              {item.icon}
              <Text 
                style={{ 
                  fontSize: '10px', 
                  marginTop: '2px',
                  color: currentView === item.value ? themeColors.primary : themeColors.text.secondary
                }}
              >
                {item.emoji}
              </Text>
            </Button>
          ))}
        </div>
      </Layout>
    );
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* PC端侧边栏 */}
      <div style={sidebarStyle}>
        {/* 头部区域 */}
        <div style={headerSectionStyle}>
          <Avatar
            size={collapsed ? 'medium' : 'large'}
            style={{
              backgroundColor: 'rgba(255, 255, 255, 0.2)',
              marginBottom: collapsed ? spacing.xs : spacing.s,
            }}
          >
            <DashboardIcon style={{ fontSize: collapsed ? '20px' : '28px' }} />
          </Avatar>
          {!collapsed && (
            <>
              <Title level="h4" style={{ color: '#ffffff', margin: 0 }}>
                智能打字训练营
              </Title>
              <Text style={{ color: 'rgba(255, 255, 255, 0.9)', fontSize: '12px', marginTop: spacing.xs }}>
                提升你的打字技能
              </Text>
            </>
          )}
          
          {/* 折叠按钮 */}
          <button
            onClick={toggleCollapse}
            style={collapseButtonStyle}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
            }}
          >
            {collapsed ? <MenuUnfoldIcon size="16px" /> : <MenuFoldIcon size="16px" />}
          </button>
        </div>

        {/* 统计卡片 */}
        {!collapsed && (
          <>
            <div style={statsCardStyle}>
              <Text style={{ color: themeColors.text.secondary, fontSize: '12px' }}>
                今日练习统计
              </Text>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: spacing.xs }}>
                <Title level="h5" style={{ color: themeColors.primary, margin: 0 }}>
                  25 分钟
                </Title>
                <Text style={{ color: themeColors.success, fontSize: '12px' }}>
                  +5 分钟
                </Text>
              </div>
            </div>
            <Divider style={{ margin: `${spacing.s} ${spacing.m}` }} />
          </>
        )}

        {/* 菜单 */}
        <div style={{ padding: collapsed ? spacing.xs : spacing.s, flex: 1 }}>
          <Menu
            value={currentView}
            onChange={(value: string | number) => handleMenuClick(value as string)}
            style={{ backgroundColor: 'transparent', border: 'none' }}
          >
            {menuItems.map((item) => (
              <Menu.MenuItem
                key={item.value}
                value={item.value}
                icon={item.icon}
                style={{
                  borderRadius: borderRadius.medium,
                  margin: `${spacing.xs} 0`,
                  padding: collapsed ? spacing.s : `${spacing.s} ${spacing.m}`,
                  justifyContent: collapsed ? 'center' : 'flex-start',
                  transition: 'all 0.2s ease',
                }}
              >
                {collapsed ? (
                  <Tooltip content={item.label} placement="right">
                    <span>{item.icon}</span>
                  </Tooltip>
                ) : (
                  item.label
                )}
              </Menu.MenuItem>
            ))}
          </Menu>
        </div>

        {/* 版本信息 */}
        {!collapsed && (
          <div style={{ padding: spacing.m, textAlign: 'center' }}>
            <Text style={{ color: themeColors.text.secondary, fontSize: '10px' }}>
              版本 1.0.0
            </Text>
          </div>
        )}
      </div>

      {/* 主内容区域 */}
      <Content style={contentStyle}>
        <div style={contentInnerStyle}>
          {renderCurrentView()}
        </div>
      </Content>
    </Layout>
  );
};

export default MainNavigation;